import { type Ref, ref, reactive, h, onMounted, toRaw, nextTick } from "vue";
import dayjs from "dayjs";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps, LabelFormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import editForm from "../form/index.vue";
import editlabelForm from "../form/labelName.vue";
import { message } from "@/utils/message";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { deviceDetection } from "@pureadmin/utils";
import { handleTree } from "@/utils/tree";
import { hasAuth } from "@/router/utils";

import {
  getCategoryPage,
  getLabelPage,
  categoryAdd,
  categoryUpdate,
  labelAdd,
  labelUpdate,
  labelDelete
} from "@/api/basicArchives/labelmanag";

const treeLoading = ref(true);
const treeData = ref([]);

export function useLabelm(treeRef?: Ref) {
  const form = reactive({
    categoryId: undefined,
    labelName: undefined
  });

  const loading = ref(false);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100]
  });

  const columns: TableColumnList = [
    {
      label: "标签名称",
      prop: "labelName"
    },
    {
      label: "标签分类",
      prop: "categoryId",
      cellRenderer: ({ row }) => (
        <>
          <el-tag type="primary" effect="plain">
            {row.categoryName}
          </el-tag>
        </>
      )
    },
    {
      label: "创建人",
      prop: "createUserName"
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm"),
      minWidth: 120
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    const params = {
      ...toRaw(form),
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    const { data } = await getLabelPage(params);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  const formRef = ref();
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}标签分类`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          categoryName: row?.categoryName ?? undefined,
          sort: row?.sort ?? undefined
        }
      },
      width: "500px",
      sureBtnLoading: true,
      fullscreenIcon: true,
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          loadTree();
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            if (title === "新增") {
              // 表单规则校验通过
              // 实际开发先调用新增接口，再进行下面操作
              const { code } = await categoryAdd(curData);
              if (code == 200) {
                chores();
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const { code } = await categoryUpdate(curData);
              if (code == 200) {
                chores();
              }
            }
          }
          closeLoading();
        });
      }
    });
  }

  function openLableDialog(title = "新增", row?: LabelFormItemProps) {
    addDialog({
      title: `${title}标签`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          labelName: row?.labelName ?? undefined,
          categoryId: row?.categoryId ?? form.categoryId
        }
      },
      width: "500px",
      sureBtnLoading: true,
      fullscreenIcon: true,
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editlabelForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as LabelFormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            if (title === "新增") {
              // 表单规则校验通过
              // 实际开发先调用新增接口，再进行下面操作
              const { code } = await labelAdd(curData);
              if (code == 200) {
                chores();
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const { code } = await labelUpdate(curData);
              if (code == 200) {
                chores();
              }
            }
          }
          closeLoading();
        });
      }
    });
  }

  async function handleDelete(row) {
    const res = await labelDelete(row.id);
    if (res.code != 200) return;
    message(`删除成功`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 加载标签分类菜单tree */
  const loadTree = async () => {
    treeLoading.value = true;
    // 获取菜单
    let params = {
      categoryName: undefined,
      pageNum: 1,
      pageSize: 999
    };
    const { data } = await getCategoryPage(params);

    data.records.forEach(item => {
      item.parentId = 0;
      item.value = item.id;
      item.label = item.categoryName;
    });

    data.records.unshift({
      value: 0,
      id: 0,
      label: "全部",
      categoryName: "全部"
    });

    treeData.value = handleTree(data.records || []);
    // 默认选择第一个
    treeLoading.value = false;
    nextTick(() => {
      let tempData = treeData.value[0];
      treeRef && treeRef.value.setCurrentKey(tempData?.id ?? 0);
    });
  };

  function onTreeSelect(treeData) {
    let { id, selected } = treeData;
    form.categoryId = selected && id != 0 ? id : undefined;
    onSearch();
  }

  onMounted(async () => {
    onSearch();

    await loadTree();
    treeLoading.value = false;
  });

  return {
    form,
    columns,
    onSearch,
    loading,
    dataList,
    pagination,
    treeData,
    treeLoading,
    openDialog,
    useRenderIcon,
    handleDelete,
    deviceDetection,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    onTreeSelect,
    loadTree,
    openLableDialog,
    hasAuth
  };
}
